<?php
/**
 * Created by 王跃达.
 * User: 小马出行
 * Date: 2017/8/24
 * Time: 16:17
 */
namespace app\api\logic;
use app\api\logic\DriverLogic;
use app\api\logic\UserLogic;
use app\api\controller\Callback;
use app\inter\logic\OrderLogic as interOrderLogic;
use my\Tools;
use think\Db;
use think\Model;
use my\Security;
class PayLogic extends Model
{
    public function __construct()
    {
        parent::__construct();

    }

    /**
     * 微信支付、支付宝支付回调后的处理
     * @param $out_trade_no
     * @param $paytool
     * @param $account
     * @param $total_fee//单位统一为分
     */
    public function return_data($out_trade_no, $paytool, $account, $total_fee)
    {
        $flag = false;
        //***充值信息，有数据但还没有付款成功的
        $recharge_info = Db::table('xm_user_recharge')->where('out_trade_no', $out_trade_no)->where('status', 0)->find();
        //***乘车信息，下面有判断
        $order_common_info = Db::table('xm_order_common')->where('order_sn', $out_trade_no)->find();
        //***城际微信回调,下面有判断
        $inter_order_logic = new interOrderLogic();
        $inter_info = $inter_order_logic->getOrderCommon(array('order_sn'=>$out_trade_no),'*',false);
        //付款--城内
        if ($order_common_info) {
            $need_price = $order_common_info['need_price'];//乘客实际支付金额
            if ($total_fee == $need_price) {
                if($paytool == 1){
                    $type = 1;//纯支付宝支付
                }
                if($paytool == 2){
                    $type = 2;//纯微信支付
                }
                $third_pay = $total_fee;
                $wallet_pay = 0;
            } else if ($total_fee < $need_price) {
                if($paytool == 1){
                    $type = 4;//纯支付宝支付+余额//纯支付宝支付
                }
                if($paytool == 2){
                    $type = 5;//微信支付+余额
                }
                $third_pay = $total_fee;
                $wallet_pay = $need_price - $total_fee;
            }
            //***查看订单的状态是否已经大于45
            $order_status = $order_common_info['order_status'];
            if ($order_status == 40) {
                $userLogic = new userLogic();
                $userLogic->setUserMoney($order_common_info['order_sn'], $order_common_info['common_id'], $order_common_info['uid'], $type, $third_pay, $wallet_pay);
                //***更改pay_log支付日志
                $data_log['uid'] = $order_common_info['uid'];
                $data_log['common_id'] = $order_common_info['common_id'];
                $data_log['pay_time'] = time();
                $data_log['pay_type'] = $type;//1支付宝2微信3全额4支付宝+余额5微信+余额
                $data_log['pay_account'] = $account;//帐号
//                $data_log['order_type'] = $order_common_info['order_type'];//类型1出租车2网约车3城际
                Db::table('xm_pay_log')->where('common_id', $order_common_info['common_id'])->update($data_log);
                //****4,把钱给司机和给司机一条行为记录
                $driver_id = $order_common_info['driver_id'];
                $driverLogic = new driverLogic();
                if ($order_common_info['order_type'] == 1) {
                    //网约车需要扣除平台费用
                    $driver_moneyIn = $order_common_info['original_price'] - $order_common_info['platform_price'];
                } else {
                    $driver_moneyIn = $order_common_info['original_price'];
                }
                //****处理优惠卷 is_use 2未用1已用
                if ($order_common_info['coupon_id']) {
                    Db::name('coupon')->where('coupon_id', $order_common_info['coupon_id'])->update(['is_use' => 1]);
                }
                //***用户付完款给司机发送一条消息，并存入消息
                $registration_id = Db::table('xm_driver')->where('driver_id',$driver_id)->value('registration_id');
                $start_name = Security::decrypt($order_common_info['start_name']);
 //               $content = "您的订单编号{$order_common_info['order_sn']},出发时间:".date('Y-m-d H:i',$order_common_info['on_car_time']).",出发地点:{$start_name}的订单已付款。";
                $content = "你有".sprintf('%.2f',$driver_moneyIn/100) ."元车费入账,你可以在个人中心查看";

                sendjg(['type'=>'driver','registration_id'=>$registration_id], '车费入账', $content, 2);
                $mes_id = Db::name('driver_message')->insertGetId(['mes_type'=>5,'title'=>'车费入账','content'=>$content,'send_time'=>time()]);
                Db::name('driver_mes_relation')->insertGetId(['driver_id'=>$driver_id,'mes_id'=>$mes_id,'is_read'=>2]);
              
                //修改司机余额、增加一条日志，并更改司机状态为1(继续接单...)
                $driverLogic->addDriveMoney($driver_id, $driver_moneyIn,$order_common_info['common_id']);
                $flag = true;
            }
        }
        //充值功能
        elseif ($recharge_info) {
            if(empty($recharge_info['status'])){
                $res = Db::name('user_recharge')->where('out_trade_no', $out_trade_no)->update(array('status' => 1,'type'=>$paytool));
                if ($res) {
                    //***修改用户的user_wallet的余额值
                    $uid = $recharge_info['uid'];
                    $money = $recharge_info['money'];
                    $return_money = $recharge_info['return_money'] ? $recharge_info['return_money'] : 0;//充值赠送的金额
                    Db::name('user_wallet')->where('uid', $uid)->setInc('wallet_money', $money);
                    Db::name('user_wallet')->where('uid', $uid)->setInc('return_money', $return_money);
                    $flag = true;
                }
            }

        }
        //付款--城际
        elseif ($inter_info) {
            $info = $inter_info;
            if (!empty($info) && $info['order_status'] == 0) {
                //如果第三方支付的金额不是订单的应付金额，则是混合支付
                $data['order_status'] = 30;
                $data['paytool'] = $type = ($info['need_price']*100) > $total_fee ? $paytool+3 : $paytool;
                $data['third_price'] = $total_fee/100;
                $inter_order_logic->renewOrderCommon(array('id' => $info['id']),$data);
                //优惠券变为使用
                $info['coupon_id']&&$inter_order_logic->renewCoupon(array('coupon_id'=>$info['coupon_id']),array('is_use'=>1));
                //***添加log
                $data_log['uid'] = $info['member_id'];
                $data_log['common_id'] = $info['id'];
                $data_log['pay_time'] = $data['time'] = time();
                $data_log['pay_type'] = $type;//1支付宝2微信3全额4支付宝+余额5微信+余额
                $data_log['pay_account'] = $account;//帐号
                $data_log['order_type'] = 3;//类型1出租车2网约车3城际
                Db::name('pay_log')->where('common_id', $info['id'])->insert($data_log);
                //3添加一个用户流水---只记录第三方的变动
                $tmp = $total_fee/100;
                $remark = "第三方支付{$tmp}元";
                $act = 1;if(($info['user_money']*100)>0){$act=2;}
                $this->dealUserFlow($info['id'],$info['member_id'],$paytool,$total_fee,6,$info['order_sn'],$act,$remark);
                $this->dealInterOrderInform($info['id']);
                $flag = true;
            }
        }
        if($flag){
            switch ($paytool){
                //支付宝
                case 1:
                    echo 'success';die();
                    break;
                case 2:
                    $callback = new Callback();
                    $callback->replyNotify();
                    break;
                default:
                    break;
            }

        }
    }

    /**
     * 改变用户的钱包金额
     * @param $money //单位为分
     * @param $uid //用户id
     * @param $type //1为增加，2为减少
     * @param $field
     * @return  mixed
     */
    public function changeUserWallet($money,$uid,$type=1,$field='wallet_money'){
        switch ($type){
            case 1:
                return Db::table('xm_user_wallet')->where('uid',$uid)->setInc($field, $money);
                break;
            case 2:
                return Db::table('xm_user_wallet')->where('uid',$uid)->setDec($field, $money);
                break;
            default:
                return false;
        }
    }

    /**
     * 处理城际订单通知
     * @param $id;
     * */
    public function dealInterOrderInform($id)
    {
        $count = Db::table('inter_order')->where('common_id',$id)->count();
        $sql = "SELECT a.admin_id,a.user_phone,o.order_sn,o.start_time,o.start_name,o.arrive_name FROM	inter_order_common o 
        LEFT JOIN inter_car_banci b ON o.banci_id = b.id LEFT JOIN xm_admin_area aa ON b.start_address = aa.arean_id
        LEFT JOIN xm_admin a ON aa.admin_id = a.admin_id LEFT JOIN xm_css_schedule s ON s.admin_id = a.admin_id
        WHERE o.id = $id AND s.start_time < o.start_time AND s.end_time > o.start_time";
        $res = Db::query($sql);
        if(!empty($res)){
            foreach ($res as $key => $val){
                $time = date('Y-m-d H:i',$val['start_time']);
                if($key==0){
                    $content['starttime'] = $time;
                    $content['startaddress'] = $val['start_name'];
                    $content['count'] = $count;
                    Tools::sendMes($val['user_phone'],$content,3);
                }
                $push['to'] = $val['admin_id'];
                $push['type'] = 'publish';
                $push['title'] = '新订单';
                $push['content'] = "订单号:{$val['order_sn']}，出发时间:{$time}，出发地:{$val['start_name']}，目的地:{$val['arrive_name']}，乘客数:{$count}人";
                Tools::innerPush($push);
            }
        }
    }

    /**
     * 处理用户支付流水
     * @param $common_id
     * @param $uid
     * @param $type //1纯支付宝 2纯微信 3纯余额 4余额+支付宝 5余额+微信
     * @param $money //充值或消费的金额
    * @param $money_statement //1充值2城内订单消费3签到4退款5扣款6城际订单消费
     * @param $order_sn //交易号
     * @param $act //1为新增，2为更新
     * @param $remark //退款或扣款时的说明
     * */
    public function dealUserFlow($common_id,$uid,$type,$money,$money_statement,$order_sn,$act=1,$remark='')
    {
        if($act==2){
            $map['common_id'] = $common_id;
            $map['money_statement'] = $money_statement;
            $flow = Db::table('xm_user_recharge')->where($map)->field('money,remark')->find();
            $data['money'] = $flow['money'] + $money;
            $data['out_trade_no'] = $order_sn;
            $data['type'] = $type;
            if($remark){$data['remark'] = $flow['remark']?$flow['remark']."<br>".$remark:$remark;}
            Db::table('xm_user_recharge')->where($map)->update($data);
        }else{
            $data_recharge['common_id'] = $common_id;
            $data_recharge['time'] = time();
            $data_recharge['type'] = $type;//纯余额
            $data_recharge['uid'] = $uid;
            $data_recharge['money'] = $money;
            $data_recharge['status'] = 1;
            $data_recharge['money_statement'] = $money_statement;//城际订单消费
            $remark&&$data_recharge['remark'] = $remark;
            $data_recharge['out_trade_no'] = $order_sn;//消费订单号
            Db::table('xm_user_recharge')->insert($data_recharge);
        }
    }

}